package com.jisc.adaptor.datasources.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class CSVHandler extends SpreadsheetHandler {

	private String csvFilePath;
	
	private char delimeter;
	
	private boolean hasHeader;
	
	public CSVHandler(String csvFilePath, char delimeter, boolean hasHeader) throws Exception {
		super(loadCSV(csvFilePath, delimeter, hasHeader));
		this.csvFilePath = csvFilePath;
		this.delimeter = delimeter;
		this.hasHeader = hasHeader;
	}

	private static List<List<String>> getCSVData(CSVReader reader) throws Exception {
		List<List<String>> data = new ArrayList<List<String>>();
		String[] row;
		while ((row = reader.readNext()) != null) {
			data.add(Arrays.asList(row));
		}
		return data;
	}
	
	private static Data loadCSV(String csvFilePath, char delimeter, boolean hasHeader) throws Exception {
		CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(csvFilePath)));
		List<String> header;
		List<List<String>> data;
		if (hasHeader) {
			header = Arrays.asList(reader.readNext());
			data = getCSVData(reader);
		} else {
			data = getCSVData(reader);
			header = getNumberBasedHeader(getMaxCols(data));
		}
		reader.close();
		Data result = new Data(header);
		result.setRows(data);
		return result;
	}
	
	public String getCsvFilePath() {
		return csvFilePath;
	}

	public char getDelimeter() {
		return delimeter;
	}

	public boolean isHasHeader() {
		return hasHeader;
	}

	@Override
	public void save() throws Exception {
		CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(
				this.getCsvFilePath())), this.getDelimeter());
		if (this.isHasHeader()) {
			writer.writeNext(this.getData().getHeader().toArray(new String[0]));
		}
		for (List<String> row : this.getData().getRows()) {
			writer.writeNext(row.toArray(new String[0]));
		}
		writer.close();
	}
	
}
